﻿using Estsh.Core.Controllers;
using Estsh.Core.IServices;
using Estsh.Core.Model.Result;
using Estsh.Core.Models;
using Estsh.Core.Util;
using Microsoft.AspNetCore.Mvc;
using System.Collections;

/***************************************************************************************************
 * 
 * 作者：贾文涛
 * 创建时间：2013.03.19
 * 描述：菜单模块控制类
 * 修改日志：
 * 1、2013.03.27  贾文涛   变更后台的菜单表，同步变更获取菜单数据的一些方法
 * 
 * *************************************************************************************************/
namespace Estsh.Core.Web.Plugin.Wms.Controllers
{
    /// <summary>
    /// 菜单模块控制类
    /// </summary>
    [Area("wms")]
    public class MenuController : BaseController
    {
        private IMenuService service;
        public MenuController(IMenuService _service)
        {
            service = _service;
        }

        //
        // GET: /Menu/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 加载首页功能菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult getHomeMenuById(string menuId)
        {
            Hashtable result = new Hashtable();
            if (CurrentEmp != null)
            {
                result = service.getHomeMenuList(CurrentEmp, menuId);
            }

            return Json(result);
        }
        /// <summary>
        /// 加载Main页功能主菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult getMainMenuById(string menuId)
        {
            Hashtable result = new Hashtable();
            if (CurrentEmp != null)
            {
                result = service.getMainMenuList(CurrentEmp, menuId);
            }
            return Json(result);
        }

        /// <summary>
        /// 加载Main页功能子菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult getChildMenuById(string menuId)
        {
            string path = HttpContext.Request.PathBase;
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            Hashtable result = new Hashtable();
            if (CurrentEmp != null)
            {
                result = service.getChildMenuList(CurrentEmp, menuId, path);
            }
            return Json(result);
        }

        /// <summary>
        /// 加载非Tab的Main页功能子菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult getNoNTabChildMenuById(string menuId)
        {
            string path = HttpContext.Request.PathBase;
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            Hashtable result = new Hashtable();
            if (CurrentEmp != null)
            {
                result = service.getNoNTabChildMenuList(CurrentEmp, menuId, path);
            }
            return Json(result);
        }

        /// <summary>
        /// 加载功能树
        /// </summary>
        /// <returns></returns>
        public ActionResult getMenuTree()
        {
            List<TreeNode> treeNodes = new List<TreeNode>();
            string path = HttpContext.Request.PathBase;
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            Hashtable result = new Hashtable();
            if (CurrentEmp != null)
            {
                treeNodes = service.getMenuList(CurrentEmp, path);
            }
            result.Add("treeNodes", treeNodes);
            return Json(result);
        }

        /// <summary>
        /// 获取菜单管理列表数据
        /// </summary>
        /// <param name="menuName">菜单名称</param>
        /// <param name="pager">分页</param>
        /// <param name="direction">排序方式</param>
        /// <param name="sort">排序列</param>
        /// <returns></returns>
        public ActionResult getMenuListByPage(String menuName, Pager pager, String direction, String sort)
        {
            Hashtable result = new Hashtable();
            result.Add("pager.pageNo", pager.pageNo);
            Hashtable dataHt = service.getMenuListByPage(menuName, pager, direction, sort,"Y");
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            result.Add("sort", sort);
            result.Add("direction", direction);
            return Json(result);
        }

        /// <summary>
        /// 获取父节点菜单下拉列表数据
        /// </summary>
        /// <rehuoturns></returns>
        public ActionResult getSelectMenu()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = service.getSelectMenu();
            result.Add("list", menuList);
            return Json(result);
        }

        /// <summary>
        /// 保存菜单数据
        /// </summary>
        /// <returns></returns>
        public ActionResult saveMenu()
        {
            String editType = Request.Form["editType"].ToString();
            SysWebMenu menu = new SysWebMenu();
            
            menu.Name = Request.Form["menuName"].ToString();
            menu.ParentId = int.Parse(Request.Form["parentId"]);
            menu.Url = Request.Form["url"].ToString();
            menu.IconUrl = Request.Form["iconUrl"].ToString();
            menu.IconOpenUrl = Request.Form["iconOpenUrl"].ToString();
            menu.IconCloseUrl = Request.Form["iconCloseUrl"].ToString();
            menu.IconSkin = Request.Form["iconSkin"].ToString();
            menu.Enabled = Request.Form["enabled"].ToString();
            menu.Description = Request.Form["description"].ToString();
            menu.SortNum = int.Parse(Request.Form["sortNum"]);

            String message = "";
            String flag = "";
            if (editType != null && editType.Trim().Equals("edit"))
            {
                try
                {
                    menu.UpdateUserId = CurrentEmp.EmpId;
                    menu.MenuId = int.Parse(Request.Form["menuId"]);
                    service.updateMenu(menu);
                    message = "修改成功";
                    flag = "OK";
                }
                catch (Exception e)
                {
                    message = "修改失败！";
                    flag = "Fail";
                }
            }
            else
            {
                try
                {
                    menu.CreateUserId = CurrentEmp.EmpId;
                    this.service.saveMenu(menu);
                    message = "添加成功";
                    flag = "OK";
                }
                catch (Exception e)
                {
                    message = "添加失败！";
                    flag = "Fail";
                }
            }

            Hashtable result = new Hashtable();
            result.Add("message", message);
            result.Add("flag", flag);
            return Json(result);
        }

        /// <summary>
        /// 查看菜单详情
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult getMenuDetail(String menuId)
        {
            List<SysWebMenu> menus = this.service.getMenuDetail(menuId);
            if (menus != null && menus.Count > 0) 
            {
                ViewData.Add("menuId", menus[0].MenuId);
                ViewData.Add("name", menus[0].Name);
                ViewData.Add("description", menus[0].Description);
                ViewData.Add("url", menus[0].Url);
                ViewData.Add("parentId", menus[0].ParentId);
                ViewData.Add("iconUrl", menus[0].IconUrl);
                ViewData.Add("iconOpenUrl", menus[0].IconOpenUrl);
                ViewData.Add("iconCloseUrl", menus[0].IconCloseUrl);
                ViewData.Add("iconSkin", menus[0].IconSkin);
                ViewData.Add("enabled", menus[0].Enabled);
                ViewData.Add("sortNum", menus[0].SortNum);
            }

            return View("viewMenu");
        }

        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult editMenu(String menuId)
        {
            if (!string.IsNullOrEmpty(menuId))
            {
                List<SysWebMenu> menus = service.getMenuDetail(menuId);
                if (menus != null & menus.Count > 0)
                {
                    ViewData.Add("editType", "edit");
                    ViewData.Add("menuId", menuId);
                    ViewData.Add("name", menus[0].Name);
                    ViewData.Add("description", menus[0].Description);
                    ViewData.Add("url", menus[0].Url);
                    ViewData.Add("parentId", menus[0].ParentId);
                    ViewData.Add("iconUrl", menus[0].IconUrl);
                    ViewData.Add("iconOpenUrl", menus[0].IconOpenUrl);
                    ViewData.Add("iconCloseUrl", menus[0].IconCloseUrl);
                    ViewData.Add("iconSkin", menus[0].IconSkin);
                    ViewData.Add("enabled", menus[0].Enabled);
                    ViewData.Add("sortNum", menus[0].SortNum);
                }
            }
            else
            {
                ViewData.Add("editType", "new");
            }
            return View("editMenu");
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult deleteMenu(String ids)
        {
            int delCount = 0;
            try
            {
                delCount = service.deleteMenu(ids);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 获取操作权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getButtonList()
        {
            List<SysProgramFunOp> result = new List<SysProgramFunOp>();
            String path = Request.PathBase;
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            Uri? uri = Request.GetTypedHeaders().Referer;
            string urlStr = string.Empty;
            if (uri != null)
            {
                urlStr = uri.AbsolutePath;
                if (!string.IsNullOrEmpty(path))
                {
                    urlStr = urlStr.Substring(urlStr.LastIndexOf(path) + path.Length);
                }
                if (uri.AbsoluteUri.Split('?').Length > 1)
                {
                    urlStr = urlStr + "?" + uri.AbsoluteUri.Split('?')[1];
                }
            }
            
            string opType = HttpContext.Request.Form["opType"];
            string gridName = HttpContext.Request.Form["gridName"];
            if (CurrentEmp != null && !string.IsNullOrEmpty(urlStr))
            {
                result = service.getOpMenuList(CurrentEmp, urlStr, opType, gridName);
            }
            return Json(result);
        }


        /// <summary>
        /// 获取小尺寸工具栏
        /// </summary>
        /// <returns></returns>
        public ActionResult getMinToolbar()
        {
            List<string> result = new List<string>();
            try
            {
                String path = Request.PathBase;
                if (path.EndsWith("/"))
                {
                    path = path.Substring(0, path.Length - 1);
                }
                
                Uri? uri = Request.GetTypedHeaders().Referer;
                string urlStr = string.Empty;
                if (uri != null)
                {
                    urlStr = uri.AbsolutePath;
                    if (!string.IsNullOrEmpty(path))
                    {
                        urlStr = urlStr.Substring(urlStr.LastIndexOf(path) + path.Length);
                    }
                    if (uri.AbsoluteUri.Split('?').Length > 1)
                    {
                        urlStr = urlStr + "?" + uri.AbsoluteUri.Split('?')[1];
                    }
                }

                string opType = HttpContext.Request.Form["opType"];
                if (CurrentEmp != null && !string.IsNullOrEmpty(urlStr))
                {
                    result.Add(service.getMinToolbar(CurrentEmp, urlStr, opType));
                }

            }
            catch (Exception e)
            {
                result.Add(e.Message);
            }

            return Json(result);
        }
    }
}
